/**
 * 会话面板部分，包含工具条及消息框。 
 */
var ChatPanel = (function(){    
    var _userMarkerTmp = [
        '<div>',
            '<h4 class="userNameTip" title="<%=o.user.name%>">',
                '<%=o.user.name%>',                
            '</h4>',
            '<div style="margin-left: -2px;">',
                '<img src="/ujs/images/common32/<%=o.terminal || "web" %>.png" title="<%=o.terminal%>" class="mapUserTerminal" />',
                '<%= lan("misc.locateBy", o.ltype || "web") %>',
            '</div>',            
            '<div style="width:140px;">',
                '<%= lan("misc.atSomeTime", (new Date(o.ltime || o.eventTime)).format("dd-MN hh:mm:ss")) %>',
            '</div>',
            '<div>',
                '<button class="userMarkerBtn kick" uid="<%=o.user.id%>" lan="buttons.kickOutChat"></button>',
                '<button class="userMarkerBtn chat" uid="<%=o.user.id%>" lan="buttons.chat">Chat</button>',
            '</div>',
        '</div>'
    ].join('');
        
    function _chatPanel(chatGroupEntity){
        this.teid = chatGroupEntity['id'] || chatGroupEntity['teid'];
        this.chatGroupEntity = chatGroupEntity;
    }
    
    _chatPanel.prototype.init = function(){
        var _this = this;
        if(this.$container){
            if(!this.isInited){
                this.$wrapper = $(ChatPanelView.main).appendTo(this.$container);
                this.$participantListWrapper = this.$wrapper.find('.chatPanelParticipantsWrapper'); 
                this.$participantAdderWrapper = this.$wrapper.find('.participantAdderWrapper');    
                this.$chatPanelContent = this.$wrapper.find('.chatPanelContent');
                this.$chatEditor = this.$wrapper.find('.chatEditor');
                this.$chatViewer = this.$wrapper.find('.chatViewer');
                this.$chatLeft = this.$wrapper.find('.chatLeft');
                this.$chatMap = this.$wrapper.find('.chatMap');
                        
                var chatBoxHeight = $.cookie('chatBoxHeight');
                if(chatBoxHeight){
                    chatBoxHeight = parseInt(chatBoxHeight);                    
                } else {
                    chatBoxHeight = $(window).height() / 5;
                }
                _this.$chatEditor.height(chatBoxHeight);
                _this.$chatViewer.css('height', 'calc(100% - {0}px)'.format(chatBoxHeight + 21));
                                                
                this.isDraging = false;
                this.isVDraging = false;
                var $hSpliter = this.$wrapper.find('.h_spliter');
                var $vSpliter = this.$wrapper.find('.v_spliter');
                this.$chatEditor.delegate('.chatEditorToolbar', 'mousedown', function(e){
                    _this.isDraging = true;    
                    _this.startY = e.pageY;                          
                    $('body').addClass('unselectable');
                });
                
                $hSpliter.bind('mousedown', function(e){
                    _this.isDraging = true;    
                    _this.startY = e.pageY;                          
                    $('body').addClass('unselectable');               
                });
                $vSpliter.bind('mousedown', function(e){
                    _this.isVDraging = true;
                    _this.startX = e.pageX;      
                    $('body').addClass('unselectable');               
                });
                 
                 //默认v offset.
                _this.startOffset = 20;
                
                $(document.body).bind({
                    'mouseup' : function(e){
                        if(_this.isVDraging && _this.map){
                            google.maps.event.trigger(_this.map, 'resize');
                        }
                        _this.isDraging = false;
                        _this.isVDraging = false;
                        $('body').removeClass('unselectable');
                    },
                    'mousemove' : function(e){
                        if(_this.isDraging){                            
                            var offsetY = e.pageY - _this.startY;
                            _this.startY = e.pageY;
                            var editorHeight = _this.$chatEditor.height() - offsetY;
                            editorHeight = editorHeight.constraintRegion(55, 450);
                            $.cookie('chatBoxHeight', editorHeight);
                            _this.$chatEditor.height(editorHeight);
                            _this.$chatViewer.css('height', 'calc(100% - {0}px)'.format(editorHeight + 21));
                        }
                        if(_this.isVDraging){                            
                            var offsetX = e.pageX - _this.startX;
                            _this.startX = e.pageX;
                            var startOffset = _this.startOffset + offsetX;
                            startOffset = startOffset.constraintRegion(-500, 500);
                            _this.startOffset = startOffset;
                            _this.$chatLeft.css('width', 'calc(50% + {0}px)'.format(startOffset));                            
                            _this.$chatMap.css('width', 'calc(50% - {0}px)'.format(startOffset));
                        }
                    }
                });
                
                this.$chatMemberView = this.$participantListWrapper.find('.chatPanelParticipantsList');
                //hide member view.   
                _this.$chatMemberView.delegate('.closeChatMemberViewBtn', 'click', function(){
                    _this.hideParticipants();
                });  
                
                if(!_this.chatGroupEntity.te){
                    _this.chatGroupEntity.te = {};
                }
                
                if(!_this.chatGroupEntity.te.creator){
                    _this.chatGroupEntity.te.creator = {};
                }
                
                if(_this.chatGroupEntity.te.creator && _this.chatGroupEntity.te.creator.id != ujs.util.session.getCurrentUserID()){
                    _this.$participantListWrapper.find('.adminSIcon').css('cursor', 'default');                    
                }
                
                _this.$chatMemberView.delegate('.adminSIcon', 'click', function(){
                    if(!_this.chatGroupEntity.te.perm.adm || _this.chatGroupEntity.te.creator.id != ujs.util.session.getCurrentUserID() || _this.chatGroupEntity['type'] == ChatGroupType.SINGLECHAT){                        
                        return false;
                    }                    
                    var $self = $(this),
                        tip,
                        tipFun;
                        userName = $self.parent().find('.chatMemberName').text();
                        
                    function getAdmin(){
                        return _this.$participantListWrapper.find('.adminSIcon.creator, .adminSIcon.admin').map(function(){
                            return $(this).attr('uid');    
                        }).get();    
                    }
                        
                    function saveAdmin(){                        
                        var data = {
                            auids : getAdmin()
                        };   
                        page.biz.updateChatGroup(_this.teid, Object.toFormData({
                            chat : JSON.stringify(data)
                        }), function(msg){});     
                    }
                    if($self.hasClass('admin')){
                        tip = 'Do you want to remove group {0}\'s admin role?'.format(userName);  
                        tipFun = function(){               
                            $self.removeClass('admin').addClass('user').attr('src', '/ujs/images/common16/user2.png');
                            $self.parent().find('.closeBtn').attr('style', '');
                        };  
                    } else {
                        if($self.hasClass('user')){
                            if(getAdmin().length > 9){
                                bubble.msg('Admins cannot be more than ten');
                                return false;
                            }
                            tip = 'Do you want to set {0} as admin'.format(userName);
                            tipFun = function(){                                
                                $self.removeClass('user').addClass('admin').attr('src', '/ujs/images/common16/user3.png');
                                $self.parent().find('.closeBtn').attr('style', 'display:none;');
                            };
                        };
                    }
                    if(tip && tipFun){
                        bubble.confirm(tip, function(){
                            tipFun();
                            saveAdmin();    
                        });     
                    }               
                    return false;
                });   
                //hide add member view.
                _this.$participantListWrapper.delegate('.closeAddChatMemberViewBtn', 'click', function(){
                    _this.$participantAdderWrapper.slideUp();
                });
                
                _this.$chatMemberView.delegate('.chatMember', 'click', function(){
                    var id = $(this).attr('id');
                    var type = $(this).attr('type');    //group 20, user 10
                    var entity = _this.parts.findOne(function(item){
                        return item.id == id;
                    });
                    if(type == '20'){                    
                        ujs.ui.Dialog.get( GroupProfileViewerDialog ,{
                            title : lan('dialog.title.detail'),
                            group : entity,
                            perm : {
                                chat : 1
                            } 
                        });
                    } else {
                        ujs.ui.Dialog.get( UserProfileViewerDialog ,{
                            title : lan('dialog.title.detail'),
                            user : entity,
                            perm : _this.chatGroupEntity['perm']
                        });        
                    }
                });
                //adder
                _this.$chatMemberView.delegate('.chatMemberAdder', 'click', function(){
                    
                    if(_this.chatGroupEntity['type'] == ChatGroupType.SINGLECHAT){
                        var user = page.biz.getParticipant(_this.chatGroupEntity);    
                        user.type = 10;                
                        ujs.ui.Dialog.get( ChatGroupDialog, {
                            title : lan('app.im.chat.newChat'),
                            initMembers : [user]
                        });
                        return false;    
                    }
                    
                    _this.$participantAdderWrapper.slideDown();
                                        
                    var $adder = $(ChatPanelView.participantAdder);
                    var $chatMemberAddList = _this.$participantAdderWrapper.find('.chatMemberAddList'); 
                    $chatMemberAddList.html('');
                    $adder.appendTo($chatMemberAddList);
                    _this.memberSelector = new MemberSelector($adder.find('.memberSelector3'), {
                        width : 595,
                        height : 120,
                        treeType : 'adminchat',
                        mode : 'expand',
                        clickable : false                        
                    });
                    //add participant.
                    $adder.delegate('.saveChatMemberViewBtn', 'click', function(){                        
                        var members = _this.memberSelector.getUserAndGroup();    
                        if(members['groups'].length || members['users'].length){                    
                            page.biz.updateChatGroup(
                                _this.chatGroupEntity['id'],
                                Object.toFormData({
                                    chat : JSON.stringify({
                                        aug : members['groups'],
                                        au : members['users']
                                    })
                                }), 
                                function(msg){                            
                                    _this.loadParticipants();  
                                    _this.$participantAdderWrapper.slideUp();   
                                    _this.hideParticipants();           
                                }
                            );   
                        } else {
                            bubble.msg(lan('app.im.participant.selectTip'));
                        } 
                        return false;
                    });
                });   
                _this.$chatMemberView.delegate('.closeBtn', 'click', function(){
                    var $chatMemberItem = $(this).closest('.chatMember');
                    var joined = $(this).attr('joined') == 'true';
                    
                    var memberID = $chatMemberItem.attr('id'),
                        memberType = $chatMemberItem.attr('type');
                    var doneDelete = ujs.hr(function(msg){
                        $chatMemberItem.animate({
                            scale : 0.1
                        }, 500, function() {
                            $(this).remove();
                        });                          
                    });
                    bubble.confirm(lan('app.im.participant.delTip'), function(){                            
                        if(joined){
                            if(_this.chatGroupEntity.type === 'locationalert'){
                                $.ajax({
                                    type : 'delete',
                                    url : '/apis/usergroup/{userGroupId}/user/{userId}'.format({
                                        userGroupId : _this.chatGroupEntity['id'],
                                        userId : memberID    
                                    }),
                                    success : doneDelete
                                });
                            } else {
                                if(_this.chatGroupEntity.type === 'event'){
                                    $.ajax({
                                        type : 'delete',
                                        url : '/apis/usergroup/{userGroupId}/user/{userId}'.format({
                                            userGroupId : _this.$chatMemberView.attr('xxxID'),
                                            userId : memberID    
                                        }),
                                        success : doneDelete
                                    });
                                }
                            }    
                        } else {
                            var deleteData = {};
                            if(memberType == MemberType.GROUP){
                                deleteData['rug'] = [memberID];
                            } else {
                                deleteData['ru'] = [memberID];
                            }             
                            page.biz.updateChatGroup(
                                _this.chatGroupEntity['id'],
                                Object.toFormData({
                                    chat : JSON.stringify(deleteData)
                                }), 
                                doneDelete
                            );
                        }    
                    }); 
                    return false;                                     
                });
                //chatPanel header及toolbar.
                this.chatViewHeader = new ChatViewHeader(this);
                this.chatDialogToolbar = new ChatViewToolbar(this);                
                //消息工具条.
                this.msgEditorToolbar = new MsgEditorToolbar(this);                
                //消息输入框.
                this.chatEditorBox = new MsgEditor(this);                
                //消息显示板.
                this.chatView = new ChatView(this);
                                
                if(ChatGroupPerm.check(this.chatGroupEntity.perm, ChatGroupPerm.DISPLAYMAP)){                    
                    this.$chatLeft.css('width', 'calc(50% + 20px)');                    
                    ujs.subjects.map.GoogleMapAPI.load(function(){
                        (function(){
                            _this.initLocation(_this.$wrapper.find('.chatMap').show());    
                        }).defer(500);                                
                    }, _this.$wrapper.find('.chatMap').get(0));
                } else {
                    _this.$wrapper.find('.chatMap').hide();
                }
                        
                this.$replyToBroadcaster = _this.$wrapper.find('.replyToBroadcaster');
                var func = this.chatGroupEntity.perm.func;
                if(func && func.contains('bre')){
                    this.$wrapper.find('.chatViewer').css({
                        height : 'calc(100% - 57px)'
                    });
                    this.$replyToBroadcaster.click(function(){
                        var uid = _this.chatGroupEntity.te.creator['id'];
                        var singleChat = page.chatGroupStore.getSingleChatByUser(uid);                    
                        if(singleChat){
                            sessionList.startSession(singleChat['id']);                            
                        } else {           
                            page.biz.createChatGroup(
                                Object.toFormData({
                                    chat : JSON.stringify({
                                        type : 'singlechat',
                                        uids : [uid]
                                    })
                                }), 
                                function(msg){                            
                                    //add local
                                    page.biz.addChatGroupLocal(msg);                                    
                                    sessionList.startSession(msg['te']['id']);                            
                                }
                            );
                        }
                    });    
                } else {
                    this.$replyToBroadcaster.remove();    
                }
                
                this.isInited = true;
            }
        }
    };
    
    _chatPanel.prototype.initLocation = function($dialogContent){
        var _this = this;
        
        //存储 markers.
        _this.markers = {};
        
        var extra = _this.chatGroupEntity.extraProps;                            
        if(extra){
            var lon = extra.lo;
            var lat = extra.la;
            var zoom = extra.zoom;
        } else {
            var lon = 40;
            var lat = 40;
            var zoom = 10;
        }
             
        var latlon = new google.maps.LatLng(lat, lon);
        _this.center = latlon;
        
        //----------------------------------------------------------------
        
        var map = new google.maps.Map(
            $dialogContent.find('.map-wrapper-google').get(0), 
            $.extend({}, ujs.subjects.map.GoogleMapAPI.mapDefConfig, {
                center : latlon,
                zoom : zoom
            })
        );       
        
        google.maps.event.addListener(map, "click", function(event) {            
            _this.$mResult.hide();
        });        
        google.maps.event.addListener(map, "rightclick", function(event) {            
            _this.$mResult.hide();
        }); 
                       
        var $searchBox = $([
        	'<div style="position:relative;">',
        		'<input type="text" class="pac-input controls" placeholder=" Search users" style="font-size: 16px;"/>',
        		'<div style="display:none;background: rgba(230, 232, 247, 0.93);" class="m-result"></div>',
    		'<div>'
		].join(''));
		
		var $input = $searchBox.find('input');
		_this.$input = $input;
		var $mResult = $searchBox.find('.m-result');
        _this.$mResult = $mResult;
        
        map.controls[google.maps.ControlPosition.TOP_LEFT].push($searchBox.get(0));
        
        
        $input.on('focus', function(){
        	_this.$mResult.show();
        	console.log('focus');
        });
        
        $input.on('keyup', function(e){
        	_this.$mResult.show();
        	console.log('change');
        	        	
        	_this.$mResult.find('.m-item').filterByText($(this).val().trim());        	
        });
        
        $input.keypress(function(e) {
		  	if (e.which == 13) {
		    	_this.$mResult.find('.m-item:visible').trigger('click');
		    	_this.$mResult.hide();
		  	}
		});

        $searchBox.delegate('.m-item','click', function(){        	
            if(_this.markers){
            	Object.each(_this.markers, function(key, markerTmp){ 
            	    if(markerTmp && markerTmp.infoWindow && markerTmp.infoWindow.close){
    				    markerTmp.infoWindow.close();
    				}
            	});
            	var markerTmp = _this.markers[$(this).attr('v')];        	
            	if(markerTmp){
        			map.setCenter(markerTmp.getPosition()); 
        			markerTmp.infoWindow.open(_this.map, markerTmp);
    			}
    			_this.$mResult.hide();
			}
        });
        
        map.maxZIndex = 100000;

        // Create a marker for each place.
        var marker = new google.maps.Marker({
            map : map,
            icon : {
                url : '/ujs/app/im/images/marker/36.png',
                size : new google.maps.Size(36, 53),
                origin : new google.maps.Point(0, 0)
            },
            title : '',
            position : latlon
        });   
        
        this.map = map;
      
        google.maps.event.addListener(marker, 'mouseover', function() {
            map.maxZIndex = map.maxZIndex || 100000;
        }); 
    };
    
    _chatPanel.prototype.getHeaderPlaceholder = function(){
        return this.$wrapper.find('.chatViewerHeaderLeft');
    };
    
    _chatPanel.prototype.getHeaderToolbarPlaceholder = function(){
        return this.$wrapper.find('.chatViewerHeaderRight');
    };
    
    _chatPanel.prototype.getMsgboxToolbarPlaceholder = function(){
        return this.$wrapper.find('.chatEditorToolbar');
    };
    
    _chatPanel.prototype.getMsgboxPlaceholder = function(){
        return this.$wrapper.find('.chatEditorBox');
    };
    
    _chatPanel.prototype.getChatViewPlaceholder = function(){
        return this.$wrapper.find('.chatViewer');
    };
    
    //----------------------------------------------------------------------
    
    _chatPanel.prototype.disableChatEditor = function(){
        this.$wrapper.find('.chatEditor').hide();
        this.$wrapper.find('.chatViewer').css({
            height : 'calc(100% - 20px)'
        });
    };
    
    _chatPanel.prototype.enableChatEditor = function(){
        this.$wrapper.find('.chatEditor').show();
        this.$wrapper.find('.chatViewer').css({
            height : 'calc(100% - 167px)'
        });
    };
    
    _chatPanel.prototype.setKeys = function(keys){
        this.keys = keys;
        var m = new ujs.ui.CommonHighlighter();
        m.mark(this.keys.join(' '), this.$wrapper.get(0));
    };
    
    //----------------------------static method---------------------------
    
    /**
     * 判断是否是活跃的聊天窗口.
     */
    _chatPanel.isActiveChatPanel = function(chatGroupID){
        var activeChatPanel = ChatPanel.getActiveChatPanel();
        return activeChatPanel && activeChatPanel.chatGroupEntity['id'] == chatGroupID && activeChatPanel.mode != 'view';
    };
    
    _chatPanel.isActiveLocationAlert = function(chatGroupID){
        var activeChatPanel = ChatPanel.getActiveChatPanel();
        return activeChatPanel && activeChatPanel.chatGroupEntity['id'] == chatGroupID && activeChatPanel.map;
    };
    
    /**
     * 获取活跃的ChatPanel. 
     */
    _chatPanel.getActiveChatPanel = function(){
        if(!page || !page.contentCardLayout){
            return null;
        }
        var activeChatPanel = page.contentCardLayout.getActiveItem();
        if(activeChatPanel && activeChatPanel.constructor === ChatPanel){            
            return activeChatPanel;
        }
    };

    /**
     * 获取活跃的ChatView. 
     */
    _chatPanel.getActiveChatView = function(){        
        var activeChatPanel = ChatPanel.getActiveChatPanel();;
        if(activeChatPanel){            
            return activeChatPanel.chatView;
        }         
    };    
    
    //--------------------------------------------------------------------------------------    
        
    _chatPanel.prototype.loadParticipants = function(cb){
        var _this = this,
            teid = this.chatGroupEntity['id'];
        //参与者数据.
        var participantPromise = $.get('/apis/chat/{0}'.format(teid));        
        var handler = function(msg, tmpUsers){                        
            var users = msg['te']['participants'];
            
            var xxxID = null;
            var filteredUsers = [];
            for(var i=0; i<users.length; i++){
                if(users[i]['id'] != teid && users[i]['ugtype'] != 10){
                    filteredUsers.push(users[i]);
                } else {
                    xxxID = users[i]['id'];
                }
            }
            users = filteredUsers;
            
            if(_this.chatGroupEntity.type == 'event'){
                _this.$chatMemberView.attr('xxxID', xxxID);
                $.ajax({
                    url : '/apis/usergroup/{0}/subusers'.format(xxxID),
                    async : false,
                    success : ujs.hr(function(msg){
                        for(var j=0; j<msg['users'].length; j++){  
                            msg['users'][j]['joined'] = true;                      
                        }
                        users = users.add(msg['users']);
                    }) 
                });
            }
            
            if(tmpUsers && tmpUsers['users'] && tmpUsers['users'].length){
                users = users.add(tmpUsers['users']);
            }
            users.sort(function(a, b){
                return parseInt(a.type) <= parseInt(b.type);    // ? true : (parseInt(a.type) == parseInt(b.type) ? a.name < b.name : false);
            });
       
            _this.parts = users;
            
            _this.$chatMemberView.html(tmpl(ChatPanelView.participantList, {
                participants : users
            }));         
            
            var isSingleChat = ChatGroupType.SINGLECHAT == _this.chatGroupEntity.type;
            
            if(!isSingleChat){
                _this.$chatMemberView.find('.p_search').searchable({
                    placeholder : 'Search ...',
                    isShowSearchBtn : false,
                    style : 'margin-right: 10px;margin-top: 3px;',
                    boxStyle : 'zoom: 0.8;width:120px;',
                    onKeyup : function(val){                    
                        _this.$chatMemberView.find('.chatMember').filterByText(val, '.chatMemberName');
                    },
                    //搜索提交时.
                    onSearch : function(val, searchType, $searchBox) {},
                    //取销搜索时.
                    onCancelSearch : function($searchBox) {                    
                        _this.$chatMemberView.find('.chatMember').filterByText('', '.chatMemberName');
                    }
                });
            } else {
                _this.$chatMemberView.find('.userIconList').remove();
            } 
            
            if(!isSingleChat){
                _this.$chatMemberView.find('.p_kind').selectBox({
                    width: 60,
                    style : 'line-height: 20px;min-width: 80px;vertical-align: middle;',                
                    value : 'all',
                    data : [{
                        text : 'Users',
                        value : 'all'
                    }, {
                        text : 'Admins',
                        value : 'admin'
                    }],
                    onchange : function(val){
                        if(val == 'admin'){
                            _this.$chatMemberView.find('.chatMember').hide();
                            _this.$chatMemberView.find('.chatMember').filter(function(){
                                return $(this).find('.adminSIcon.admin, .adminSIcon.creator').length > 0;
                            }).show();
                        }
                        if(val == 'user'){
                            _this.$chatMemberView.find('.chatMember').hide();
                            _this.$chatMemberView.find('.chatMember').filter(function(){
                                return $(this).find('.adminSIcon.admin, .adminSIcon.creator').length == 0;
                            }).show();
                        }
                        if(val == 'all'){
                            _this.$chatMemberView.find('.chatMember').show();                      
                        }
                    }
                });
            }
               
            _this.$chatMemberView.find('#' + _this.chatGroupEntity['id']).find('.chatMemberName').text(_this.chatGroupEntity['name']);                            
            if(!ChatGroupPerm.check(_this.chatGroupEntity['perm'], ChatGroupPerm.DELETEPARTICIPANTS)){
                _this.$chatMemberView.find('.chatMember .closeBtn').remove();
            }                
            if(!ChatGroupPerm.check(_this.chatGroupEntity['perm'], ChatGroupPerm.ADDPARTICIPANTS)){
                _this.$chatMemberView.find('.chatMemberAdder').remove();
            }       
            
            if(_this.chatGroupEntity.te.perm.adm && _this.chatGroupEntity.te.creator.id == ujs.util.session.getCurrentUserID() && _this.chatGroupEntity['type'] != ChatGroupType.SINGLECHAT){                        
                _this.$chatMemberView.find('.chatMemberList').addClass('administrator');
            }
                 
            cb && cb(msg);
        };
        
        if(this.chatGroupEntity.type == 'locationalert'){
            //临时组数据.
            var tempGroupUserPromise = $.get('/apis/usergroup/{0}/subusers'.format(teid));
            $.when(participantPromise, tempGroupUserPromise).done(function(participantResult, tempUserResult){
                for(var jj=0; jj<tempUserResult[0]['users'].length; jj++){  
                    tempUserResult[0]['users'][jj]['joined'] = true;                      
                }
                handler(participantResult[0], tempUserResult[0]);
            });    
        } else {
            $.when(participantPromise).done(function(msg, status, xhr){
                handler(msg);
            });
        }
    };
            
    _chatPanel.prototype.showParticipants = function(){    
        var _this = this;    
        _this.loadParticipants(function(msg){
            _this.$participantListWrapper.slideDown();
        });    
    };
    
    _chatPanel.prototype.hideParticipants = function(){
        if(this.$participantListWrapper){
            this.$participantListWrapper.slideUp();
        }
    };
    
    _chatPanel.prototype.showMask = function(){
        this.$chatPanelContent.showMask('loading');
    };
    
    _chatPanel.prototype.hideMask = function(){
        this.$chatPanelContent.hideMask();
    };
    
    _chatPanel.prototype.scan = function(){
        var lon = 40;
        var lat = 40;
        var extra = this.chatGroupEntity.extraProps;                            
        if(extra){
            lon = extra.lo;
            lat = extra.la;
        }        
        $.ajax({
            type : 'post',
            url : '/apis/location/request/now',
            data : {
                lo : lon,
                la : lat,             
                id : this.chatGroupEntity['id'],
                ugids : [this.chatGroupEntity['id']],
                obj : 'now'
            }            
        });
    };
    
    _chatPanel.prototype.addUser = function(evt){
        var _this = this;
        var teid = evt['teid'];
        var user = evt['user'];
        var uid = evt['user']['id'];
        var latlng = new google.maps.LatLng(evt['la'], evt['lo']);
        
        //若处于当前会话窗口.                   
        if(evt['obj'] != 'now'){ //将用户添加到当前会话.
            $.ajax({
                type : 'post',                         
                url : '/apis/usergroup/{0}/user/{1}'.format(teid, uid)
            });
        }                    
        
        var marker = _this.markers[uid];
        if(marker){
            marker.setVisible(false);
            marker.setMap(null);
            if(marker.infoWindow){
                marker.infoWindow.close();
                marker.infoWindow = null;
            }
            _this.markers[uid] = null;                        
            marker = null;                        
        } else {
        	_this.$mResult.append('<div class="m-item" v="{0}">{1}</div>'.format(uid, user['name']));
        }
        
        marker = new google.maps.Marker({
            map : _this.map,
            icon : {
                url : '/ujs/app/im/images/marker/man.gif',//place.icon,
                size : new google.maps.Size(11, 24),
                origin : new google.maps.Point(0, 0)
            },
            title : user['name'],
            position :  latlng,
            crossOnDrag : false,
            raiseOnDrag : false
        });  
        _this.markers[uid] = marker;
        
        //距中心距离.
        var disMarker = '0';
        if(_this.center){
            disMarker = Math.getDistance(
                _this.center.lat(), 
                _this.center.lng(), 
                latlng.lat(), 
                latlng.lng()
            );
        }
        user['dis'] = (disMarker / 1000).toFixed();
        
        //marker tooltip window.
        var $infoW = $(tmpl(_userMarkerTmp, $.extend(true, {}, evt)));      
        lan.parse($infoW);
          
        $infoW.on('click', function(){                            
            ujs.ui.Dialog.get( UserProfileViewerDialog , {
                kick : '/apis/usergroup/{userGroupId}/user/{userId}'.format({
                    userGroupId : teid,
                    userId : user['id']    
                }),
                afterKick : function(){
                    marker.setMap(null);
                },
                title : 'Profile',
                user : user,
                perm : _this.chatGroupEntity['perm'] 
            });
        });
        
        $infoW.delegate('button', 'click', function(){
            var $btn = $(this);
            if($(this).hasClass('chat')){
                var uid = $btn.attr('uid');
                var singleChat = page.chatGroupStore.getSingleChatByUser(uid);                    
                if(singleChat){
                    sessionList.startSession(singleChat['id']);                    
                } else {           
                    page.biz.createChatGroup(
                        Object.toFormData({
                            chat : JSON.stringify({
                                type : 'singlechat',
                                uids : [uid]
                            })
                        }), 
                        function(msg){                            
                            //add local
                            page.biz.addChatGroupLocal(msg);                            
                            sessionList.startSession(msg['te']['id']);                            
                        }
                    );
                }  
            } else {
                bubble.confirm(lan('app.im.participant.kickOutTip', user['name']), function(){
                    $.ajax({
                        type : 'delete',
                        url : '/apis/usergroup/{userGroupId}/user/{userId}'.format({
                            userGroupId : teid,
                            userId : user['id']    
                        })
                    }).then(function(){
                        _this.markers[user['id']] = null;                        
                        
                        _this.$mResult.find('.m-item[v={0}]'.format(user['id'])).remove();                      
                        
                        marker.setMap(null);
                    }); 
                });
            }  
            return false;  
        });
            
        var infowindow = new google.maps.InfoWindow({
            content: $infoW.get(0)
        });
        //infowindow.open(_this.map, marker);        
        marker.infoWindow = infowindow;
                
        google.maps.event.addListener(infowindow, 'mouseover', function() {
            infowindow.setZIndex(_this.map.maxZIndex+=1);
        });
        google.maps.event.addListener(infowindow, 'domready', function() {
              $infoW.parent().parent().on('mouseover', function(){
                  infowindow.setZIndex(_this.map.maxZIndex+=1);
              });
        }); 
        
        google.maps.event.addListener(marker, 'click', function() {
            var markerSelf = this;
            
            Object.each(_this.markers, function(key, markerTmp){        		 
				markerTmp.infoWindow.close();
        	});
        	
            infowindow.setZIndex(_this.map.maxZIndex+=1);
            infowindow.open(_this.map,markerSelf);                            
        });
        google.maps.event.addListener(marker, 'mouseover', function() {
            infowindow.setZIndex(_this.map.maxZIndex+=1);
            console.log('mouseover');
        });    
    };
    
    return _chatPanel;
})();